<template>
  <div>
    <div class="app-container">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleAddClick"
        style="margin-bottom: 15px"
      >
        新增特别关注点
      </el-button>

      <el-table v-loading="loading" :data="tableData">
        <el-table-column label="内容" prop="name" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              type="primary"
              @click="handleEditClick(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDeleteClick(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
        style="margin-top: 15px; text-align: center"
      />

      <el-dialog
        :title="dialogStatus === 'create' ? '新增特别关注点' : '编辑特别关注点'"
        :visible.sync="dialogVisible"
        width="500px"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="100px"
          label-position="right"
        >
          <el-form-item label="内容" prop="name">
            <el-input
              v-model="form.name"
              type="textarea"
              :rows="4"
              placeholder="请输入特别关注点内容"
            />
          </el-form-item>
          <el-form-item label="科目" prop="subjectId">
            <el-cascader
              v-model="selectedSubjectPath"
              :options="subjectTree"
              :props="{ checkStrictly: true, emitPath: true }"
              placeholder="请选择课程"
              filterable
              clearable
              @change="handleSubjectChange"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import specialCareApi from "@/api/specialCare/index";
import subjectApi from "@/api/subject/index";
import { Message, MessageBox } from "element-ui";

export default {
  name: "SpecialCare",
  data() {
    return {
      tableData: [],
      loading: false,
      total: 0,
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogStatus: "create",
      form: {
        id: undefined,
        name: "",
        subjectId: undefined,
      },
      rules: {
        name: [
          { required: true, message: "请输入特别关注点内容", trigger: "blur" },
          {
            min: 1,
            max: 500,
            message: "长度在 1 到 500 个字符",
            trigger: "blur",
          },
        ],
        subjectId: [
          { required: false, message: "请选择科目", trigger: "change" },
        ],
      },
      subjectTree: [], // 存储树形结构数据
      selectedSubjectPath: [], // 存储级联选择器选中的路径
    };
  },
  created() {
    this.fetchData();
    this.getSubjectList();
  },
  methods: {
    async fetchData() {
      try {
        this.loading = true;
        const res = await specialCareApi.page(this.currentPage, this.pageSize);
        if (res.code === 20000) {
          this.tableData = res.data.records;
          this.total = res.data.total;
        }
      } catch (error) {
        console.error("获取特别关注点列表失败", error);
        Message.error("获取特别关注点列表失败");
      } finally {
        this.loading = false;
      }
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.fetchData();
    },
    handleAddClick() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogVisible = true;
    },
    handleEditClick(row) {
      this.resetForm();
      this.dialogStatus = "update";
      this.form = {
        id: row.id,
        name: row.name,
        subjectId: row.subjectId || undefined,
      };
      // 如果有 subjectId，找到对应的路径
      if (row.subjectId) {
        this.findSubjectPath(this.subjectTree, row.subjectId);
      } else {
        this.selectedSubjectPath = [];
      }
      this.dialogVisible = true;
    },
    handleDeleteClick(row) {
      MessageBox.confirm("确定要删除该特别关注点吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await specialCareApi.delete(row.id);
            if (res.code === 20000) {
              Message({
                type: "success",
                message: "删除成功!",
              });
              this.fetchData();
            }
          } catch (error) {
            console.error("删除特别关注点失败", error);
            Message.error("删除失败，请重试");
          }
        })
        .catch(() => {
          // 取消删除
        });
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: "",
        subjectId: undefined,
      };
      this.selectedSubjectPath = [];
      // 如果表单已经渲染，则重置校验结果
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            let res;
            if (this.dialogStatus === "create") {
              res = await specialCareApi.add(this.form);
            } else {
              res = await specialCareApi.update(this.form);
            }

            if (res.code === 20000) {
              Message({
                type: "success",
                message:
                  this.dialogStatus === "create" ? "新增成功!" : "更新成功!",
              });
              this.dialogVisible = false;
              this.fetchData();
            }
          } catch (error) {
            console.error(
              this.dialogStatus === "create"
                ? "新增特别关注点失败"
                : "更新特别关注点失败",
              error
            );
            Message.error(
              this.dialogStatus === "create"
                ? "新增失败，请重试"
                : "更新失败，请重试"
            );
          }
        } else {
          return false;
        }
      });
    },
    async getSubjectList() {
      try {
        const res = await subjectApi.getAllTree();
        if (res.code === 20000) {
          this.subjectTree = this.processTreeData(res.data);
        }
      } catch (error) {
        console.error("获取科目列表失败", error);
        Message.error("获取科目列表失败");
      }
    },
    handleSubjectChange(value) {
      // 当级联选择器值变化时，将最后一个值赋给 subjectId
      if (value && value.length > 0) {
        this.form.subjectId = value[value.length - 1];
      } else {
        this.form.subjectId = undefined;
      }
    },
    // 处理树结构，移除空的 children 数组
    processTreeData(treeData) {
      return treeData.map((node) => {
        const processedNode = { ...node };

        // 如果 children 是空数组，则删除该属性
        if (processedNode.children && processedNode.children.length === 0) {
          delete processedNode.children;
        } else if (processedNode.children) {
          // 递归处理子节点
          processedNode.children = this.processTreeData(processedNode.children);
        }

        return processedNode;
      });
    },
    // 递归查找节点路径
    findSubjectPath(tree, targetId, currentPath = []) {
      for (const node of tree) {
        // 创建新路径，包含当前节点
        const path = [...currentPath, node.value];

        // 如果找到目标节点
        if (node.value === targetId) {
          this.selectedSubjectPath = path;
          return true;
        }

        // 如果有子节点，递归查找
        if (node.children && node.children.length > 0) {
          if (this.findSubjectPath(node.children, targetId, path)) {
            return true;
          }
        }
      }

      return false;
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
